import re
def initial(s,show):
    # s 传入的算数表达式--字符串 show--控制计算结果显示
    s = s.replace(' ','')
    # 去除字符串中的空格
    operand = re.findall(r'\d+',s)
    operator = re.findall(r'[^\d]',s)
    print(operand)
    print(operator)
    if len(operand)>2 or len(operator) > 1:
        return "Error: Numbers must only contain digits."
    elif len(operand[0])> 4 or len(operand[1])>4 :
        '''操作数不大于4位数'''
        return "Error: Numbers cannot be more than four digits."
    elif not (operator[0]  in ('+','-')):
        '''操作符非法'''
        return "Error: Operator must be '+' or '-'."
    
    maxlen = max(len(operand[0]),len(operand[1]))
    cover = [operand[0].rjust(maxlen+2),operator[0]+' '+operand[1].rjust(maxlen),'-'*(maxlen+2)]
     # 表达式格式化输出
        #       操作数
        # 操作符 操作数
        # 分割线------
    if show:
        if operator[0] == '+':
            cover.append(str(int(operand[0])+int(operand[1])).rjust(maxlen+2))
        elif operator[0] == '-':
            cover.append(str(int(operand[0])-int(operand[1])).rjust(maxlen+2))
    return cover

def arithmetic_arranger(problems,show=False):
    if len(problems)>5 :
        return "Error: Too many problems."
    
    seperator = ' '*4

    covers = []
    
    for s in problems:
        '''遍历列表，依次计算，判断终止符'''
        covers.append(initial(s,show))
        if type(covers[-1])==str:
            return covers[-1]

    results = ''
    # 存储所有输出
    line = 4 if show == True else 3
    for i in range(line):
        for j in covers:
            results += j[i]+seperator
            '''每两个垂直表达式之间隔4个空格'''
            if j == covers[-1]:
                results = results[0:-4]
                #显示最后5个表达式
        results += '\n'
        # 格式化输出，换行
    return results[0:-1]
    # 返回所有表达式

    

if __name__ == "__main__":
        # print(arithmetic_arranger(["44 + 815", "909 - 2", "45 + 43", "123 + 49", "888 + 40"],True))  
    print(arithmetic_arranger(["44 + 815", "909 - 2", "45 + 43", "123 + 49"],True))  
